package io.shuttle.mbe_app

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.provider.Settings
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.OnBackPressedCallback
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Column
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Create
import androidx.compose.material.icons.filled.Face
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.material.icons.filled.Place
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.Star
import androidx.compose.material.icons.filled.Warning
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.BasicAlertDialog
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.core.net.toUri
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewmodel.compose.viewModel
import com.github.only52607.compose.window.ComposeFloatingWindow
import com.github.only52607.compose.window.LocalFloatingWindow
import com.github.only52607.compose.window.dragFloatingWindow
import io.shuttle.mbe_app.components.DialConfig
import io.shuttle.mbe_app.components.DialControlBox
import io.shuttle.mbe_app.components.rememberDialState
import io.shuttle.mbe_app.ui.AppGraph
import io.shuttle.mbe_app.ui.theme.MbeTheme
import io.shuttle.mobilebrowserextension.R

class MainActivity : ComponentActivity() {
    private val floatingWindow by lazy {
        createFloatingWindow()
    }
    private var lastTs = -1L

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()

        onBackPressedDispatcher.addCallback(object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                val ts = System.currentTimeMillis()
                if (lastTs == -1L || ts - lastTs >= 2000) {
                    Toast.makeText(
                        this@MainActivity,
                        "再次点击退出",
                        Toast.LENGTH_SHORT
                    ).show()
                    lastTs = ts
                } else {
                    finish()
                }
            }

        })
        setContent {
            val showDialogPermission = remember { mutableStateOf(false) }

            LaunchedEffect(null) {
                if (floatingWindow.isAvailable()) {
                    this@MainActivity.show()
                } else {
                    showDialogPermission.value = true
                }
            }
            MbeTheme {
                Surface {
                    AppGraph()
                    DialogPermission(showDialogState = showDialogPermission)
                }

            }
        }
    }


    private fun createFloatingWindow(): ComposeFloatingWindow =
        ComposeFloatingWindow(applicationContext).apply {
            setContent {
                FloatingWindowContent()
            }
        }

    private fun show() {
        floatingWindow.show()
    }

    private fun hide() {
        floatingWindow.hide()
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun FloatingWindowContent(
    model: FloatingWindowViewModel = viewModel()
) {
    val context = LocalContext.current
    val floatingWindow = LocalFloatingWindow.current

    val dialState = rememberDialState<ImageVector>(
        listOf(
            Icons.Default.Add,
            Icons.Default.Create,
            Icons.Default.Star,
            Icons.Default.PlayArrow,
            Icons.Default.KeyboardArrowUp,
            Icons.Default.Face
        ),
        onSelected = {},
    )

// Cause Crash!!!
//    if (model.dialogVisible) {
//        BasicAlertDialog(
//            onDismissRequest = { model.dismissDialog() },
//        ) {
//            Text("system Dialog")
//        }
//    }
    FloatingActionButton(
        modifier = Modifier.dragFloatingWindow(),
        onClick = {
            model.showDialog()
        }) {
        Column {
            DialControlBox(
                options = dialState.options,
                onSelected = { selected ->
                    Toast.makeText(context, "Selected: $selected", Toast.LENGTH_SHORT)
                        .show()
                },
                optionContent = { value, selected ->
                    IconButton(onClick = {}) {
                        Icon(imageVector = value, contentDescription = value.name)
                    }
                }) {
                Icon(imageVector = Icons.Default.Place, contentDescription = "Place")
            }
        }
    }
}

class FloatingWindowViewModel : ViewModel() {
    private var _dialogVisible by mutableStateOf(false)
    val dialogVisible: Boolean get() = _dialogVisible

    fun showDialog() {
        _dialogVisible = true
    }

    fun dismissDialog() {
        _dialogVisible = false
    }
}

@Composable
fun DialogPermission(
    showDialogState: MutableState<Boolean> = mutableStateOf(false),
    permission: String = Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
    onDismiss: () -> Unit = { }
) {
    var showDialogPermission by remember { showDialogState }
    val context = LocalContext.current
    if (showDialogPermission.not()) return
    AlertDialog(
        icon = {
            Icon(
                Icons.Default.Warning,
                contentDescription = stringResource(R.string.permission_required)
            )
        },
        title = {
            Text(text = stringResource(id = R.string.permission_required))
        },
        text = {
            Text(text = stringResource(R.string.message_permission_to_draw_on_top_others_apps))
        },
        onDismissRequest = onDismiss,
        confirmButton = {
            TextButton(
                onClick = {
                    showDialogPermission = false
                    context.requestPermission(permission)
                }
            ) {
                Text(stringResource(R.string.grant_permission))
            }
        },
        dismissButton = {
            TextButton(
                onClick = {
                    showDialogPermission = false
                }
            ) {
                Text(stringResource(R.string.cancel))
            }
        }
    )
}

private fun Context.requestPermission(permission: String) {
    startActivity(
        Intent(
            permission,
            "package:$packageName".toUri()
        ).apply {
            addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        })
}